package io.renren.modules.cli.oauth2;

import io.renren.modules.cli.entity.CliUserEntity;
import io.renren.modules.cli.entity.CliUserTokenEntity;
import io.renren.modules.cli.service.CliShiroService;
import io.renren.modules.sys.entity.SysUserEntity;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Set;

/**
 * 认证
 *
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2017-05-20 14:00
 */
@Component
public class CliOAuth2Realm extends AuthorizingRealm {
    @Autowired
    private CliShiroService cliShiroService;

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof CliOAuth2Token;
    }

    /**
     * 授权(验证权限时调用)
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SimpleAuthorizationInfo info = null;
        try {
            if(principals.getPrimaryPrincipal() instanceof CliUserEntity){
                CliUserEntity user = (CliUserEntity) principals.getPrimaryPrincipal();
                Long userId = user.getUserId();

                //用户权限列表
                Set<String> permsSet = cliShiroService.getUserPermissions(userId);

                info = new SimpleAuthorizationInfo();
                info.setStringPermissions(permsSet);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return info;
    }

    /**
     * 认证(登录时调用)
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        SimpleAuthenticationInfo info = null;
        try {
            String accessToken = (String) token.getPrincipal();

            //根据accessToken，查询用户信息
            CliUserTokenEntity tokenEntity = cliShiroService.queryByToken(accessToken);
            //token失效
            if (tokenEntity == null || tokenEntity.getExpireTime().getTime() < System.currentTimeMillis()) {
                throw new IncorrectCredentialsException("token失效，请重新登录");
            }

            //查询用户信息
            CliUserEntity user = cliShiroService.queryUser(tokenEntity.getUserId());
            //账号锁定
            if (user.getStatus() == 0) {
                throw new LockedAccountException("账号已被锁定,请联系管理员");
            }

            info = new SimpleAuthenticationInfo(user, accessToken, getName());
        } catch (IncorrectCredentialsException e) {
            e.printStackTrace();
        } catch (LockedAccountException e) {
            e.printStackTrace();
        }
        return info;
    }
}
